#!/usr/bin/env python
# _*_coding:utf-8_*_

from PySide6.QtCore import *
from driver.switch_driver import SwitchDriver
import time
from my_log.logger import logger


class Signal(QObject):
    startSignal = Signal(object, int)


class ControlSwitchThread(QRunnable):
    def __init__(self, address, num):
        super(ControlSwitchThread, self).__init__()
        self.singal = Signal()
        self._isPause = False
        self.status = 0
        self.isStart = False
        self.cond = QWaitCondition()
        self.mutex = QMutex()
        self.num = num
        self.flag = True
        self.address = address
        self.switch = SwitchDriver(self.address)

    def run(self):
        time.sleep(2)
        self.open_switch()
        try:
            self.mutex.lock()
            for i in range(1, int(self.num) + 1):
                if self.flag:
                    if self._isPause:
                        self.cond.wait(self.mutex)
                    self.close_switch()
                    time.sleep(8)
                    self.singal.startSignal.emit(1, i)
                else:
                    break
            self.mutex.unlock()
        except Exception as e:
            logger.error("ControlSwitchThread," + str(e))

    def open_switch(self):
        self.switch.open()

    def close_switch(self):
        self.switch.close()

    def pause(self):
        self._isPause = True
        if self.status == 0:
            self.open_switch()
        elif self.status == 1:
            self.close_switch()

    def resume(self):
        self._isPause = False
        self.cond.wakeAll()

    def stop(self):
        self.flag = False
        if self.switch:
            self.switch.close_com()
